package pl.wroc.uni.ii.puzzle.view;

import java.util.Date;

import pl.wroc.uni.ii.puzzle.activity.PuzzleActivity;
import pl.wroc.uni.ii.puzzle.data.DatabaseAdapter;
import pl.wroc.uni.ii.puzzle.data.Score;
import pl.wroc.uni.ii.puzzle.game.Board;
import pl.wroc.uni.ii.puzzle.game.FlashBoard;
import pl.wroc.uni.ii.puzzle.game.PlayBoard;
import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View {

	private static final int START_LEVEL = -1;
	private static final int MAX_LEVEL = 9;

	private Board board;
	private int screenWidth;
	private int screenHeight;
	private int currentLevel;
	private String hardship;
	private long finishTimeMillis;
	private long startTimeMillis;
	private Score score;

	public GameView(Context context, String hardship) {
		super(context);
		this.hardship = hardship;
		currentLevel = START_LEVEL;
	}

	public void startNewLevel() {
		currentLevel++;
		if (currentLevel > MAX_LEVEL) {
			finish();
		}
		else if (currentLevel % 2 == 0) {
			board = new PlayBoard(this, currentLevel, screenWidth, screenHeight, hardship);
		}
		else {
			board = new FlashBoard(this,currentLevel);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			int x = (int) event.getX();
			int y = (int) event.getY();
			board.select(x ,y);
			invalidate(); // request onDraw()
		}
		return true;
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		board.draw(canvas);
	}

	private void finish() {
		finishTimeMillis = System.currentTimeMillis();
		try {
			persistScore();
		} catch (Exception e) {
			Log.e(GameView.class.getName(), "can't persist score", e);
		}
		PuzzleActivity puzzle = (PuzzleActivity) getContext();
		puzzle.endGameWithScore(score);
	}

	private void persistScore() throws Exception {
		Long timeSpanMillis = finishTimeMillis - startTimeMillis;
		score = new Score(timeSpanMillis, "user", new Date(), hardship);
		DatabaseAdapter databaseAdapter = new DatabaseAdapter(getContext());
		databaseAdapter.open();
		databaseAdapter.insertHighScore(score);
		databaseAdapter.close();
	}

	public void start() {
		screenWidth = getMeasuredWidth();
	    screenHeight = getMeasuredHeight();
		startNewLevel();
		startTimeMillis = System.currentTimeMillis();
	}
}